package com.yunhan.security;


import com.yunhan.utils.ResponseUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;

;

/**
 * springSecurity配置类
 */
@Slf4j
@Configuration
public class SecurityConfiguration {
    @Resource
    private UserCache userCache;

    @Resource
    private UserDetailsService userDetailsService;




    /**
     * 组装spring-security组件
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 配置跨域支持
                .cors(AbstractHttpConfigurer::disable)
                // 禁用CSRF保护
                .csrf(AbstractHttpConfigurer::disable)
                // 设置会话管理为无状态
                .sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 放行所有请求
                .authorizeHttpRequests(authz ->
                        authz.anyRequest().permitAll());

        return http.build();
    }




    //授权拒绝处理器
    @Bean
    public AccessDeniedHandler accessDeniedHandler(){
        return (request, response, accessDeniedException) -> {
            log.error("AccessDeniedHandler：权限不足");
            ResponseUtil.writeResponse(response, 403, accessDeniedException.getMessage());
        };
    }


    //密码编解码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}